package mongoclient

import (
	"context"
	"fmt"
	"sync"

	"github.com/tidwall/gjson"
	"gitlab.sy.soyoung.com/go/library/service/conf"
	"gitlab.sy.soyoung.com/go/library/service/logger"
	"gitlab.sy.soyoung.com/go/library/service/qconf"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

var mongoConns = map[string]*Engine{}
var connLock sync.Mutex

type Conn struct {
	Url    string
	Client *mongo.Client
}
type Engine struct {
	Url      string
	Client   *mongo.Client
	database string
}

func GetConn(dbname string) *Engine {
	if mongoConns[dbname] != nil {
		return mongoConns[dbname]
	}
	mongoConns[dbname] = createConn(dbname)
	// go func() {
	// 	ticker := time.NewTicker(time.Second * 10)
	// 	defer ticker.Stop()
	// 	for {
	// 		<-ticker.C
	// 		if err := mongoConns[dbname].Client.Ping(context.TODO(), nil); err != nil {
	// 			alarm.PushMsg(alarm.MsgOption{
	// 				Content: alarm.Content{
	// 					Text: fmt.Sprintf("mongo数据库%s连接已断开:%s, 尝试重新连接\n", dbname, err.Error()),
	// 				},
	// 			})
	// 			mongoConns[dbname] = createConn(dbname)
	// 		}
	// 	}
	// }()
	return mongoConns[dbname]
}
func createConn(dbname string) *Engine {
	connLock.Lock()
	defer connLock.Unlock()
	//db_ai
	dbAiUrl := getUri(dbname)
	maxPoolSize := conf.GetInt("mongo.max_pool_size")
	minPoolSize := conf.GetInt("mongo.min_pool_size")
	client, err := mongo.Connect(
		context.TODO(), options.Client().ApplyURI(dbAiUrl),
		options.Client().SetMaxPoolSize(uint64(maxPoolSize)),
		options.Client().SetMinPoolSize(uint64(minPoolSize)),
	)

	if err != nil {
		logger.Info("mongo connect fail", err)
	}
	return &Engine{
		Url:      dbAiUrl,
		Client:   client,
		database: dbname,
	}
}

//qconf获取连接地址
func getUri(serverName string) (dbUrl string) {
	uris, err := qconf.GetWebConfig("mongodb_cluster", nil)
	if err != nil {
		fmt.Println("conf", err)
	}
	dbUrl = gjson.Get(uris, serverName).String()
	return
}
